<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle">
    <BasicForm @register="registerForm" class="menuForm" />
    <template #footer>
      <a-button @click="handleSubmit(false)" type="primary" ghost>仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" >保存并关闭</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema, ComponentTypes } from "../data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import * as menuApi from "/@/api/iam/menu"
  import * as resourceApi from "/@/api/iam/resource"
  import { useAdapt } from "/@/hooks/system/useAutoAdapt"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { isArray } from "lodash"
  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const { width } = useAdapt({ xl: 700, lg: 700, md: 700, sm: 700, xs: 700 })
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const menuType = ref("0")
  const apiNamespaceCode = ref()
  const isButton = (type) => type === "2"
  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 20 },
    },
    schemas: formSchema,
    showActionButtonGroup: false,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    console.timeEnd("menu-drawer")
    await resetFields()
    console.log('data', data)
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    apiNamespaceCode.value = data.apiNamespaceCode
    menuType.value = data?.record?.menuType

    updateSchema([
      {
        field: "parentId",
        componentProps: {
          placeholder: "根节点",
          api: menuApi.listMenu,
          immediate: true,
          params: {
            apiNamespaceCode: apiNamespaceCode.value
          },
        },
      },
      {
        field: "name",
        label: isButton(unref(menuType)) ? "按钮/权限" : "菜单名称",
      },
      {
        field: "url",
        required: !isButton(unref(menuType)),
      },
      {
        field: "apiActions",
        componentProps: {
          showSearch: true,
          api: async () => {
            const data = await resourceApi.listApiResource({ apiNamespaceCode: apiNamespaceCode.value })
            data.forEach((e) => {
              e.apiSummary = e.apiAction + "  " + e.apiSummary
            })
            return data
          },
          labelField: "apiSummary",
          valueField: "apiAction",
          optionFilterProp: "label",
          onSelect: (value: any, option: any) => {
            const name = option.label.replace(" ", "").replace(value, "")
            setFieldsValue({ name })
            setDrawerProps({ loading: false })
          },
        },
      },
    ])

    let values = { 
      ...(data.record || {}), 
      apiActions: data.record?.apiActions,
      apiNamespaceCode: apiNamespaceCode.value 
    }
    setFieldsValue(values)
    setProps({ disabled: !attrs.showFooter })
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增菜单" : "编辑菜单"))

  async function handleSubmit(isClose) {
    try {
      const values = await validate()
      console.log("submit menu: ", values)

      // 去掉 values.component开头的/
      if (values.component && values.component.indexOf("/") == 0) {
        values.component = values.component.slice(1)
      }

      // iframe兼容
      if (ComponentTypes.IFrame === values.component) {
        values.component = values.frameSrc
      }

      if (isUpdate.value && values.parentId === values.id) {
        createMessage.error("上级分类不能选择自己")
        return
      }

      setDrawerProps({ loading: true })
      //提交表单 groupCodeList
      await menuApi.saveOrUpdateMenu({ 
        ...values, 
        apiActions: values.apiActions?.split(',') || [],
        apiNamespaceCode: apiNamespaceCode.value 
      }, unref(isUpdate))
      isClose && closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
      await setFieldsValue({ apiActions: [], mergeApiAction: true, name: null })
    } finally {
      setDrawerProps({ loading: false })
    }
  }
</script>
